package tech.summerly.weather.component.adapter

import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_city.view.*
import tech.summerly.weather.R
import tech.summerly.weather.model.UserRegion
import tech.summerly.weather.util.ViewHolder

class UserRegionAdapter(
        private val itemClick: (UserRegion) -> Unit
) : RecyclerView.Adapter<ViewHolder>() {

    private val items = ArrayList<UserRegion>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(R.layout.item_city, parent, LayoutInflater.from(parent.context))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = with(holder.itemView) {
        val item = getItem(position).region
        textCity.text = item.name
        textParent.text = item.province
        setOnClickListener {
            itemClick(getItem(position))
        }
    }

    fun submitList(newList: List<UserRegion>) {
        val diffResult = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return items[oldItemPosition].id == newList[newItemPosition].id
            }

            override fun getOldListSize(): Int = items.size

            override fun getNewListSize(): Int = newList.size

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return items[oldItemPosition].fullAddress == newList[newItemPosition].fullAddress
            }
        }, true)
        items.clear()
        items.addAll(newList)
        diffResult.dispatchUpdatesTo(this)
    }

    fun removeAt(position: Int) = items.removeAt(position)

    fun add(position: Int, userRegion: UserRegion) = items.add(position, userRegion)

    fun getItem(position: Int) = items[position]

    fun getItemOrNull(position: Int) = items.getOrNull(position)

    override fun getItemCount() = items.size

}